//
//  InformationViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/8/10.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import PKHUD

enum InformationType {
  case unknown, agreement, tokenRechargeInstruction
}

class InformationViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet weak var webView: UIWebView!
  
  
  // MARK: - Private vars
  
  
  
  // MARK: - Private methods
  
  private func loadInformation() {
    func handleError() {
      HUD.flash(.labeledError(title: "信息读取失败", subtitle: "请重试"), delay: 1.5)
      self.navigationController?.popViewController(animated: true)
    }
    
    var urlString: String? = nil
    switch informationType {
    case .agreement:
      urlString = APIURLStrings.getAgreement
    case .tokenRechargeInstruction:
      urlString = APIURLStrings.getTokenRechargeInstruction
    default:
      break
    }
    
    if let urlString = urlString {
      HUD.show(.labeledProgress(title: "请稍后", subtitle: nil))
      API.shared.requestAPI (
        urlString,
        method: .get,
        successCallback: { json in
          if let content = json["content"].string {
            HUD.hide()
            self.webView.loadHTMLString(content, baseURL: nil)
          } else {
            handleError()
          }
      }) { (message, code) in
        loggingPrint("Load help detail failed. \(message)")
        handleError()
      }
    }
  }
  
  // MARK: - Public vars
  
  var informationType: InformationType = .unknown
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // Do any additional setup after loading the view.
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    loadInformation()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
}

extension InformationViewController: UIWebViewDelegate {
  func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.injectDefaultStyle()
  }
  
  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
    if navigationType == .linkClicked {
      if let url = request.url {
        let alert = UIAlertController (
          title: "即将跳转到浏览器打开链接",
          message: "继续吗？",
          cancelTitle: "取消",
          cancelHandler: nil,
          confirmTitle: "继续") { _ in
            UIApplication.shared.open(url)
        }
        present(alert, animated: true)
      }
      return false
    } else {
      return true
    }
  }
}
